package com.yunao.web.utils;

import com.google.gson.Gson;
import com.yunao.commons.utils.HttpRequest;
import com.yunao.commons.utils.HttpResponse;
import com.yunao.web.wechat.object.AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

public class WechatUtils {
    private static Logger logger = LoggerFactory.getLogger(WechatUtils.class);
    public static AccessToken accessToken= null;
    public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static Gson gson = new Gson();
    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    public static AccessToken getAccessToken(String appid, String appsecret) {
        //获取access_token
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = null;
        try {

            HttpResponse httpResponse = new HttpRequest().sendGet(url, null);
            json = httpResponse.getContent();
//            System.out.println(json);
            AccessToken accessToken = gson.fromJson(json, AccessToken.class);
            WechatUtils.accessToken = accessToken;

            logger.info("刷新access_token成功 ");

        } catch (Exception e) {
            logger.error("获取access_token失败！");
            logger.error(json);
        }

        return accessToken;

    }
    /*
    * String url编码
    * */
    public static String urlEncode(String url) throws UnsupportedEncodingException {
        if(url == null) {
            return null;
        }

        final String reserved_char = ";/?:@=&";
        String ret = "";
        for(int i=0; i < url.length(); i++) {
            String cs = String.valueOf( url.charAt(i) );
            if(reserved_char.contains(cs)){
                ret += cs;
            }else{
                ret += URLEncoder.encode(cs, "utf-8");
            }
        }
        return ret.replace("+", "%20");
    }

}
